package com.lych.server.service;

import cn.hutool.core.collection.CollUtil;
import com.lych.dubbo.api.*;
import com.lych.model.domain.UserInfo;
import com.lych.model.mongo.Questions;
import com.lych.model.mongo.Soul;
import com.lych.model.mongo.SoulReport;
import com.lych.model.mongo.SoulUser;
import com.lych.model.vo.SoulReportVo;
import com.lych.model.vo.SoulVo;
import com.lych.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class SoulService {

    @DubboReference
    private SoulUserApi soulUserApi;

    @DubboReference
    private SoulApi soulApi;

    @DubboReference
    private QuestionsApi questionsApi;

    @DubboReference
    private SoulReportApi soulReportApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 测灵魂-问卷列表
     * @return
     */
    public List<SoulVo> soulPage() {
        //得到当前用户id
        Long userId = UserHolder.getUserId();
        //根据用户id查询问卷用户关系表
        List<SoulUser> soulUserList = soulUserApi.findByid(userId);
        //通过问卷用户关系表中的问卷id查询问卷详细信息
        List<String> soulIds = CollUtil.getFieldValues(soulUserList, "soulId", String.class);
        List<Soul> soulList = soulApi.findByIds(soulIds);
        //通过问卷id查询试题
        List questionsList = questionsApi.findByIds(soulIds);
        //构造对象返回
        List<SoulVo> vos = new ArrayList<>();
        for (int i = 0; i < soulUserList.size(); i++) {
            SoulVo vo = new SoulVo();
            SoulUser soulUser = soulUserList.get(i);
            Soul soul = soulList.get(i);
            //处理为前端需要的数据
            List<Questions> list = (List<Questions>) questionsList.get(i);
            List<Map> retQuestionsList = new ArrayList<>(); //构造返回问题的容器
            //构造问题的返回数据
            for (Questions questions : list) {
                Map map = new HashMap();
                String id = questions.getId();
                String question = questions.getQuestion();
                List<Map> options = questions.getOptions();
                map.put("id",id);
                map.put("question",question);
                map.put("options",options);
                retQuestionsList.add(map);
//                System.out.println(JSON.toJSONString(retQuestionsList));
            }
            BeanUtils.copyProperties(soulUser,vo);
            BeanUtils.copyProperties(soul,vo);

            vo.setQuestions(retQuestionsList);
            vos.add(vo);
        }
        return vos;
    }

    /**
     * 测灵魂-提交问卷
     * @param map
     * @return
     */
    public String soulCommit(Map map) {
        //得到操作用户数据
        Long userId = UserHolder.getUserId();
        //得到map中的数据
        List<Map> answers = (List) map.get("answers");
        ArrayList<String> nums = new ArrayList<>(); //存储用户的选择，用来统计分数
        String id = null;  //为了知道用户填的是哪一套试题
        for (Map answer : answers) {
            String optionId = (String) answer.get("optionId");
            nums.add(optionId);
            id = (String) answer.get("questionId");
        }
        //统计用户答题得分
        Integer score = sumScore(nums);
        //将分数添加到表中，用于之后查询与你相似，还要将后一级的试卷打开
        String soulReportId = soulUserApi.addScore(score,id,userId);
        return soulReportId;
    }

    //构造用户得分
    public Integer sumScore(ArrayList<String> nums){
        Integer score = 0;
        for (int i = 0; i < nums.size(); i++) {
            switch (nums.get(i)) {
                case "1":
                    score += 1;
                    break;
                case "2":
                    score += 2;
                    break;
                case "3":
                    score += 3;
                    break;
                case "4":
                    score += 4;
                    break;
                case "5":
                    score += 5;
                    break;
                case "6":
                    score += 6;
                    break;
                case "7":
                    score += 7;
                    break;
            }
        }
        return score;
    }

    /**
     * 测灵魂-查看结果
     * @param soulReportId 结果报告id
     * @return
     */
    public SoulReportVo reportId(String soulReportId) throws InterruptedException {
        //根据报告id查询对应的分数
        SoulUser soulUser = soulUserApi.findBySoulReportId(soulReportId);
        Integer score = soulUser.getScore();
        //通过分数构造鉴定结果与鉴定图片
        Map<String,String> map = findWithScore(score);
        //构造维度
        List<Map> dimensions = new ArrayList<>();
        for (int i = 1; i <= 4; i++) {
            Map map1 = new HashMap();
            map1.put("key","外向" + i);
            map1.put("value",80+i+"%");
            dimensions.add(map1);
        }

        //构造相似用户
        String type = map.get("conclusion").substring(0,3); //拿到type
        //根据soulId和type查询报告结果表
        String soulId = soulUser.getSoulId();
        List<SoulReport> list = soulReportApi.findBySoulIdWithType(soulId,type,UserHolder.getUserId());
        List<Map> similarYou = new ArrayList<>(); //存放需要返回的相似用户数据
        if (!CollUtil.isEmpty(list)){
            //拿到相似用户id
            List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
            Map<Long, UserInfo> infoMap = userInfoApi.findByIds(ids, null);
            for (Long id : ids) {
                Map map1 = new HashMap();
                UserInfo userInfo = infoMap.get(id);
                map1.put("id",userInfo.getId().intValue());
                map1.put("avatar",userInfo.getAvatar());
                similarYou.add(map1);
            }
        }
        //存入报告信息到数据库
        SoulReport soulReport = new SoulReport();
        soulReport.setSoulId(soulId);
        soulReport.setId(soulReportId);
        soulReport.setConclusion(map.get("conclusion"));
        soulReport.setCover(map.get("cover"));
        soulReport.setDimensions(dimensions);
        soulReport.setSoulId(soulId);
        soulReport.setType(type);
        soulReport.setUserId(UserHolder.getUserId());
//        soulReport.setSimilarYou(similarYou);
        soulReportApi.save(soulReport);
        //构建vo对象返回
        SoulReportVo vo = new SoulReportVo();
        vo.setConclusion(map.get("conclusion"));
        vo.setCover(map.get("cover"));
        vo.setDimensions(dimensions);
        vo.setSimilarYou(similarYou);
        return vo;
    }

    //通过分数构造鉴定结果与鉴定图片
    private Map<String, String> findWithScore(Integer score) {
        Map<String,String> map = new HashMap<>();
        if (score < 20){
            map.put("conclusion","白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。");
            map.put("cover","https://tanhua0417.oss-cn-chengdu.aliyuncs.com//2022/04/09/9b120466-ec7b-4e86-a615-15cf4c08a605.png");
            return map;
        }else if (score < 40) {
            map.put("conclusion","狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。");
            map.put("cover","https://tanhua0417.oss-cn-chengdu.aliyuncs.com//2022/04/09/9b120466-ec7b-4e86-a615-15cf4c08a605.png");
            return map;
        }else if (score < 60) {
            map.put("conclusion","狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。");
            map.put("cover","https://tanhua0417.oss-cn-chengdu.aliyuncs.com//2022/04/09/9b120466-ec7b-4e86-a615-15cf4c08a605.png");
            return map;
        }else {
            map.put("conclusion","猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分析、较重视制度、结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责");
            map.put("cover","https://tanhua0417.oss-cn-chengdu.aliyuncs.com//2022/04/09/9b120466-ec7b-4e86-a615-15cf4c08a605.png");
            return map;
        }

    }
}
